package edu.sctu.treebuilder.day02;

/**
 * Created by apple on 05/02/2018.
 */
public class CharacterReader {

    static final char EOF = (char) -1;

    private String content;
    private int pos;

    public CharacterReader(String content) {
        this.content = content;
    }

    // 读取当前字符，并后移一位
    public char consume() {
        return content.charAt(pos++);
    }

    // 读取当前字符，不移位
    public char current() {

        if (pos >= content.length())
            return EOF;

        return content.charAt(pos);
    }

    // 只移位，不返回当前值
    public void advance() {
        this.pos++;
    }

    // 当前字符是否为字母
    public boolean matchesLetter() {

        char ch = content.charAt(pos);

        return (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z');
    }

    // 读取标签体内容，如<p>hello</p>标签中的 hello
    public String consumeData() {

        int start = pos;

        while (true) {

            char cur = content.charAt(pos);

            if (cur == '<')
                break;

            pos++;
        }

        return content.substring(start, pos);
    }

    // 读取标签名称
    // <title> 开标签遇到'>'结束
    // </title>闭标签遇到'/'结束
    public String consumeTagName() {

        int start = pos;

        while (true) {

            char cur = content.charAt(pos);

            if (cur == '>' || cur == '/')
                break;

            pos++;
        }

        return content.substring(start, pos);
    }
}
